package com.lawyer.common;

import com.lawyer.util.base64.BASE64EncoderUtil;
import com.lawyer.util.date.DateUtil;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具
 * @author: wzq
 * @since: 2018/07/18
 */
public class StringUtil {

	public static String EMPTY = "";

	protected static Logger LOGGER = LoggerFactory.getLogger(StringUtil.class);

	/**
	 * str空判断
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		if (null == str || str.equalsIgnoreCase("null") || str.equals("")) {
			return true;
		} else
			return false;
	}

	/**
	 * str不为空判断
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNotEmpty(String str) {
		if (null != str && !str.equalsIgnoreCase("null") && !str.equals("")) {
			return true;
		} else
			return false;
	}

	/**
	 * 判断是否为空
	 * 
	 * @param obj
	 * @return
	 */
	public static boolean isNotEmpty(Object obj) {
		if (null != obj && !"".equals(obj) && !"null".equals(obj)) {
			return true;
		}
		return false;
	}

	/**
	 * 把字串转化为整数,若转化失败，则返回0
	 *
	 * @param str
	 *            字串
	 * @return
	 */
	public static int strToInt(String str) {
		if (str == null) {
			return 0;
		}
		try {
			return Integer.parseInt(str);
		} catch (Exception ex) {
			LOGGER.error(  "strToInt异常", str);
		}
		return 0;
	}

	/**
	 * 把字串转化为长整型数,若转化失败，则返回0
	 *
	 * @param str
	 * @return
	 */
	public static long strToLong(String str) {
		if (str == null) {
			return 0;
		}
		try {
			return Long.parseLong(str);
		} catch (Exception ex) {
			LOGGER.error(  "strToLong异常", str);
		}
		return 0;
	}

	/**
	 * 把字串转化为Float型数据,若转化失败，则返回0
	 *
	 * @param str
	 * @return
	 */
	public static float strToFloat(String str) {
		if (str == null) {
			return 0;
		}
		try {
			return Float.parseFloat(str);
		} catch (Exception ex) {
	        LOGGER.error(  "strToFloat异常"+ str);
		}
		return 0;
	}

	/**
	 * 把字串转化为Double型数据，若转化失败，则返回0
	 * 
	 * @param str
	 * @return
	 */
	public static double strToDouble(String str) {
		if (str == null) {
			return 0;
		}
		try {
			return Double.parseDouble(str);
		} catch (Exception ex) {
			LOGGER.error( "strToDouble异常"+ str);
		}
		return 0;
	}

	/**
	 * 把字串去空
	 * 
	 * @param str
	 * @return
	 */
	public static String trimStr(String str) {
		if (str == null) {
			return "";
		}
		return str.trim();
	}

	/**
	 * 生成编号：一位字符+13位时间+2位随机数
	 * 
	 * @param pre
	 *            一位字符[用户编号用“U“,借款申请单编号”B“,投标编号用“L”,待审核机构编号用“A”,
	 *            交易号用"C",日志编号"G"]
	 * @return
	 */
	public synchronized static String getUserId(String pre) {
		AtomicInteger useratomic = new AtomicInteger();
		long now = new Date().getTime();
		String inc = to2Bit(useratomic.incrementAndGet());
		useratomic.compareAndSet(99, 0);
		int fourRandomNum = (int)(Math.random()*8999+1000);
		return pre + now + inc+fourRandomNum;
	}
//
//	/**
//	 * 生成编号：一位字符+13位时间+2位随机数
//	 *
//	 * @param pre
//	 *            一位字符[用户编号用“U“,借款申请单编号”B“,投标编号用“L”,待审核机构编号用“A”,
//	 *            交易号用"C",日志编号"G"]
//	 * @return
//	 */
//	public synchronized static String genratedId(String pre) {
////		AtomicInteger useratomic = new AtomicInteger();
////		long now = new java.util.Date().getTime();
//		String now =DateUtil.formatDateAndTimeNONULL(new Date());
//		int inc =  (int)(1+Math.random()*9) ;
////				to2Bit(useratomic.incrementAndGet());
////		useratomic.compareAndSet(99, 0);
//		LOGGER.info("inc:"+inc+",now:"+now);
//		return  now + inc;
//	}
//
//    public synchronized static String genratedIdFine(String pre) {
////		AtomicInteger useratomic = new AtomicInteger();
////		long now = new java.util.Date().getTime();
//		String now =DateUtil.formatDateAndTimeNONULL(new Date());
//		int inc =  (int)(1+Math.random()*9) ;
//
//		int threeRandomNum = (int)(Math.random()*89999+10000);
//		LOGGER.info("inc:"+inc+",now:"+now+",threeRandomNum:"+threeRandomNum);
//		return  now +inc+threeRandomNum;
//	}

	public static String to2Bit(int aa) {
		String ret = aa + "";
		while (ret.length() < 2) {
			ret = "0" + ret;
		}
		return ret;
	}


	/**
	 * 判断是否手机号码格式
	 *
	 * @param str
	 * @return
	 */
	public static boolean isMobilePhone(String str) {
		return str
				.matches("^1[0-9]{10}$");
	}

	/**
	 * 验证登录密码格式
	 *
	 * @param pwd
	 * @return
	 */
	public static String checkPassword(String pwd) {
		if (StringUtil.isEmpty(pwd)) {
			return "请填写密码";
		}
		int length = pwd.length();
		if (length < 6 || length > 16) {
			return "密码为6-16位数字和字母的组合";
		}
		String pwd_matcher = "(?![a-zA-Z]+$)(?!\\d+$)[a-zA-Z0-9]{6,16}$";
		Pattern pat = Pattern.compile(pwd_matcher);
		Matcher mat = pat.matcher(pwd);
		if (!mat.find()) {
			return "密码为6-16位数字和字母的组合";
		}
		return null;
	}

	/**
	 * 把字符串，按指字的分隔符分隔为字符串数组
	 *
	 * @param list
	 *            字符串
	 * @param seperators
	 *            分隔符
	 * @return 字符串数组
	 */
	public static String[] split(String list, String seperators) {
		return split(list, seperators, false);
	}

	/**
	 * 把字符串，按指字的分隔符分隔为字符串数组
	 *
	 * @param seperators
	 *            分隔符
	 * @param list
	 *            字符串
	 * @param include
	 *            是否需要把分隔符也返回
	 * @return 字符串数组
	 */
	public static String[] split(String list, String seperators, boolean include) {
		StringTokenizer tokens = new StringTokenizer(list, seperators, include);
		String[] result = new String[tokens.countTokens()];
		int i = 0;
		while (tokens.hasMoreTokens()) {
			result[i++] = tokens.nextToken();
		}
		return result;
	}

	/**
     * 是否为空格串(判断是否为null 、"" 或 " ") isBlank(null) = true; isBlank("") = true; isBlank(" ") = true;
     * @param str 输入的字符串
     * @return 是否为空格串
     */
    public static boolean isBlank(final String str)
    {

        boolean bResult = true;

        // 是否为空串，如果为空串直接返回
        if (StringUtil.isEmpty(str))
        {
            bResult = true;
        }
        else
        {
            // 检查字符串是否全部为空格
            for (int i = 0; i < str.length(); i++)
            {
                if (!(Character.isWhitespace(str.charAt(i))))
                {
                    bResult = false;
                    break;
                }
            }
        }

        // 全部为空格，则返回true
        return bResult;
    }


	/**
	 * 判断字符是否是日期格式
	 *
	 * @param date
	 *            字符串
	 * @return boolean
	 * @author wzq
	 */
	public static boolean isDateStringValid(String date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD");
		// 输入对象不为空
		try {
			sdf.parse(date);
			return true;
		} catch (java.text.ParseException e) {
			return false;
		}
	}

	/**
     * 获取4位随机码
     * @return
     */
    public static String getPwdCode() {
        char[] codeSerial = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        String ranNumber = "";
        // 生成一个4位数的随机码
        for (int i = 0; i < 4; i++) {
            // 取索引为0-35以内的随机数，从codeSeria中取
            int a = (new Random()).nextInt(10);
            ranNumber += codeSerial[a];
        }

        return "xrl" + ranNumber;
    }

    /**
     * 验证邮箱格式
     *
     * @author wzq
     * @param email
     * @return
     */
	public static boolean isEmail(String email) {
		if (null == email) {
			return false;
		}
		email = email.trim();
		if (isEmpty(email)) {
			return false;
		} else if (email.length() < 5 || email.length() > 32) {
			return false;
		}
		String email_matcher = "([a-zA-Z0-9]+[_|\\_|\\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\\_|\\.]?)*[a-zA-Z0-9]+\\.[a-zA-Z]{2,3}$";
		Pattern pat = Pattern.compile(email_matcher);
		Matcher mat = pat.matcher(email);
		if (!mat.find()) {
			return false;
		}
		return true;
	}
	/**
	 * 生成随机密码
	 * @param length
	 * @return
	 */
	public static String gen(int length) {
		Random r=new Random();
		String code="";

		for(int i=0;i<6;++i)
		{
			if(i%2==0) //偶数位生产随机整数
			{
				code=code+r.nextInt(10);
			}
			else//奇数产生随机字母包括大小写
			{
				int temp=r.nextInt(52);
				char x=(char)(temp<26?temp+97:(temp%26)+65);
				code+=x;
			}
		}

		return code;
	}

    /**
     * 创建token
	 *
	 * @author wzq
	 * @return
     */
	public static String createToken() {
		StringBuffer token = new StringBuffer("");
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmm");
			String value = System.currentTimeMillis() + new Random().nextInt() + "";
			MessageDigest md = MessageDigest.getInstance("md5");
			byte[] b = md.digest(value.getBytes());// 产生数据的指纹
			BASE64EncoderUtil be = new BASE64EncoderUtil();
			String ranString = be.encodeBase64(b);
			String date = sdf.format(new Date());
			for (int i = 0; i < ranString.length(); i++) {// 将时间信息插入token
				if (i == 0) {
					token.append(date.charAt(0));
				} else if (i == 3) {
					token.append(date.charAt(1));
				} else if (i == 6) {
					token.append(date.charAt(2));
				} else if (i == 9) {
					token.append(date.charAt(3));
				} else if (i == 12) {
					token.append(date.charAt(4));
				} else if (i == 15) {
					token.append(date.charAt(5));
				} else if (i == 18) {
					token.append(date.charAt(6));
				} else if (i == 21) {
					token.append(date.charAt(7));
				} else if (i == 24) {
					token.append(date.charAt(8));
				}
				token.append(ranString.charAt(i));
			}
		} catch (Exception e) {
			return null;
		}
		String regEx = "([-+*&/^()\\]\\[])";// token去除特殊字符
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(token.toString());
		return m.replaceAll("F").trim();
	}

	/**
	 * 格式化JOSN
	 * @author oudebin
	 * @createTime 2017年2月23日 下午7:42:19
	 * @param jsonStr
	 * @return
	 */
	public static String formatJson(String jsonStr) {
        if (isEmpty(jsonStr)){
        	return "";
        }
        StringBuilder sb = new StringBuilder();
        char last = '\0';
        char current = '\0';
        int indent = 0;
        for (int i = 0; i < jsonStr.length(); i++) {
            last = current;
            current = jsonStr.charAt(i);
            switch (current) {
                case '{':
                case '[':
                    sb.append(current);
                    sb.append('\n');
                    indent++;
                    addIndentBlank(sb, indent);
                    break;
                case '}':
                case ']':
                    sb.append('\n');
                    indent--;
                    addIndentBlank(sb, indent);
                    sb.append(current);
                    break;
                case ',':
                    sb.append(current);
                    if (last != '\\') {
                        sb.append('\n');
                        addIndentBlank(sb, indent);
                    }
                    break;
                default:
                    sb.append(current);
            }
        }

        return sb.toString();
    }

	 /**
	  * 添加space
	  * @author oudebin
	  * @createTime 2017年2月23日 下午7:42:04
	  * @param sb
	  * @param indent
	  */
    private static void addIndentBlank(StringBuilder sb, int indent) {
        for (int i = 0; i < indent; i++) {
            sb.append('\t');
        }
    }


	/**
	 * 将json数组转化为String型
	 *
	 * @param str
	 * @return
	 */
	public static String[] getJsonToStringArray(String str) {
		JSONArray jsonArray = JSONArray.fromObject(str);
		String[] arr = new String[jsonArray.size()];
		for (int i = 0; i < jsonArray.size(); i++) {
			arr[i] = jsonArray.getString(i);
		}
		return arr;
	}

	public static void main(String []str){
	}

	/**
	 *@Description:用于生成主键随机字符串
	 *@Author:吴志强
	 *@Since: 2017年5月23日下午5:14:51
	 *@param pre
	 *@return
	 */
	public synchronized static String getRandomStr(String pre) {
		long now = new Date().getTime();
		int inc =  (int)(1+Math.random()*9) ;
		int fourRandomNum = (int)(Math.random()*89999999+10000000);
		if(pre.length() >3){
			pre = pre.substring(0, 3);
		}
		return pre+ now + inc +fourRandomNum;
	}

	/**
	 * 获取芝麻信用
	 * @return
	 */
	public synchronized static String getZhimaTransactionId() {
		String now = DateUtil.formatDateAndTimeNONULL(new Date());
		int inc =  (int)(10000+Math.random()*89999) ;
		int fourRandomNum = (int)(Math.random()*89999999+10000000);
		return now + inc +fourRandomNum;
	}
}
